﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataControl;
using System.Data;
using System.Text;
using ATW.MT.CommonClass;
using Com.Alipay;
using System.Collections;

namespace ATW.MT.BUS
{
    public class bus_T_Request
    {
        DataAccess da = null;
        public bus_T_Request()
        {
            da = new DataAccess();
        }

        #region 方法
        /// <summary>
        /// 询价分页查询
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="status">状态 0默认（未审核） 1正常（审核通过） 2删除 3审核未通过</param>
        /// <param name="pstart">发布时间开始</param>
        /// <param name="pend">发布时间结束</param>
        /// <param name="fstart">截止时间开始</param>
        /// <param name="fend">截至时间结束</param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public DataTable RequestPagerQuery(string title, string name, string status, string pstart, string pend, int page, int pagesize)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append(@"select t1.Id,t1.RequestID,t1.title,
                        (case 
		                when t1.rowstatus=0 then '未报价项目'
		                when t1.rowstatus=1 then '已报价项目'
		                when t1.rowstatus=2 then '已删除项目'
		                when t1.rowstatus=3 then '已收到合同'
		                when t1.rowstatus=4 then '执行中合同' 
		                when t1.rowstatus=5 then '已完成合同' 
		                when t1.rowstatus=6 then '报价已确认'
		                when t1.rowstatus=7 then '已顺延项目'
		                when t1.rowstatus=8 then '已关闭项目'
                        when t1.rowstatus=9 then '待人工处理'
		                end) as rowstatus,t1.create_time,u.tauName,t1.tauLoginId
                        from T_Request t1 
                        left join T_AppUser u on t1.tauLoginId=u.tauLoginId
                        where 1=1");
            if (!String.IsNullOrEmpty(title))
            {
                sql.Append(" and t1.title like '%" + title + "%'");
            }
            if (!String.IsNullOrEmpty(name))
            {
                sql.Append(" and u.tauName like '%" + name + "%'");
            }

            if (!String.IsNullOrEmpty(status))
            {
                sql.Append(" and t1.rowstatus ='" + status + "'");
            }
            if (!String.IsNullOrEmpty(pstart))
            {
                sql.Append(" and t1.create_time>cast('" + pstart + " 00:00:00' as datetime)");
            }
            if (!String.IsNullOrEmpty(pend))
            {
                sql.Append(" and t1.create_time<cast('" + pend + " 23:59:59' as datetime)");
            }

            return da.PageSize(sql.ToString(), page, pagesize, "RequestID", "create_time desc");
        }
        /// <summary>
        /// 询价详情
        /// </summary>
        /// <param name="tdiid"></param>
        /// <returns></returns>
        public DataTable RequestDetail(string strRequestID)
        {
            try
            {
                string strUrl = common.GetUrl();
                Dictionary<string, object> Parm = new Dictionary<string, object>();
                Parm.Add("@LanId", "zh");
                Parm.Add("@RequestId", strRequestID);
                Parm.Add("@strUrl", strUrl);

                return da.GetDataTableBySPName("SP_SelectRequestDetail", Parm);
            }
            catch (Exception ex)
            {
                return new DataTable();
            }
        }
        /// <summary>
        /// 该询价是否有报价
        /// </summary>
        /// <param name="RequestDetailID"></param>
        /// <returns></returns>
        public bool HasResponse(string RequestDetailID)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(@"select isnull(ResDetailID,'') from T_RequestDetail where ReqDetailID='{0}'", RequestDetailID);
            object o = da.ExecuteScalar(sql.ToString());
            if (o != null && o.ToString() != "")
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 简要获取报价情况
        /// </summary>
        /// <param name="ResponseDetailID"></param>
        /// <returns></returns>
        public DataTable ResponseBrif(string ResponseDetailID)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(@"select ResD.num,
	                                   ResD.Single_Price,au.tauName,
	                                   ResD.deliver_time from T_ResponseDetail ResD
                                left join T_Response R on ResD.ResponseID=R.ResponseID
                                left join T_AppUser au on R.tauloginid=au.tauLoginId
                                where 1=1 and ResD.ResDetailID='{0}'", ResponseDetailID);
            return da.ExecuteDataTable(sql.ToString());
        }
        /// <summary>
        /// 检查该询价对应的安特威报价表头是否存在
        /// </summary>
        /// <param name="requestID"></param>
        /// <param name="responseID"></param>
        /// <returns></returns>
        public bool isResHeadExist(string requestID, ref string responseID)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(@"select ResponseID from T_Response where tauloginid='AntiWare' and RequestID='{0}'", requestID);
            DataTable dt = da.ExecuteDataTable(sql.ToString());
            if (dt != null && dt.Rows.Count > 0)
            {
                string _responseid = dt.Rows[0]["ResponseID"].ToString();
                if (_responseid != "")
                {
                    responseID = _responseid;
                }
            }
            return false;
        }
        /// <summary>
        /// 新增安特威报价表头
        /// </summary>
        /// <param name="resquestID"></param>
        /// <param name="responseID"></param>
        /// <returns></returns>
        public int AddResHeader(string requestID, ref string responseID)
        {
            responseID = new bus_C_Conn().getNewId();
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(@"insert into T_Response(ResponseID,RequestID,tauloginID,rowstatus) values('{0}','{1}','{2}','{3}')",
                responseID, requestID, "AntiWare", "1");
            return da.ExcuteNoQuery(sql.ToString());
        }
        /// <summary>
        /// 新增报价明细
        /// </summary>
        /// <param name="requestDetailID">询价明细ID</param>
        /// <param name="Price">单价</param>
        /// <param name="finalPrice">最终价格</param>
        /// <param name="time">交期（天数）</param>
        /// <returns></returns>
        public int AddResDetail(string requestDetailID, string ResponseID, string Price, string finalPrice, string time, ref string ResponseDetailID)
        {
            ResponseDetailID = new bus_C_Conn().getNewId();
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(@"INSERT INTO T_ResponseDetail
		                           (ResDetailID
		                           ,ResponseID
		                           ,ReqDetailID
		                           ,ProductionID
		                           ,MID_B
		                           ,MID_S
		                           ,MID_I
		                           ,SID
		                           ,PressureID
		                           ,DriveID
		                           ,ConnID
		                           ,args01
		                           ,args02
		                           ,args03
		                           ,args04
		                           ,args05
		                           ,args06
		                           ,args07
		                           ,args08
		                           ,args09
		                           ,args010
		                           ,num
		                           ,Single_Price
		                           ,finla_price
		                           ,Is_Confirmed
		                           ,IS_Responsed
		                           ,deliver_time
		                           ,rowstatus
		                           ,create_time)
		                        SELECT  '{4}','{5}',T.ReqDetailID,T.ProductionID,T.MID_B,T.MID_S,T.MID_I,T.SID
		                        ,T.PressureID,T.DriveID,T.ConnID,T.args01,T.args02,T.args03,T.args04,T.args05,T.args06
		                        ,T.args07,T.args08,T.args09,T.args010,T.Query_num,'{0}','{1}','0','1','{2}','0',GETDATE()
		                        FROM T_RequestDetail T1
		                        inner join T_RequestDetail T ON T1.ReqDetailID=T.ReqDetailID
		                        WHERE T1.ReqDetailID='{3}'", Price, finalPrice, time, requestDetailID, ResponseDetailID, ResponseID);
            return da.ExcuteNoQuery(sql.ToString());
        }
        /// <summary>
        /// 修改询价单（使通过）
        /// </summary>
        /// <param name="requestID"></param>
        /// <returns></returns>
        public bool CheckReq(string requestid)
        {
            ArrayList al = new ArrayList();
            al.Add("update T_Request set rowstatus='1' where RequestID='" + requestid + "'");
            al.Add("update T_RequestDetail set rowstatus='1' where RequestID='" + requestid + "' and rowstatus='9'");
            return da.ExecuteArrayList(al);
        }
        /// <summary>
        /// 更新询价明细
        /// </summary>
        /// <param name="requestDetailID"></param>
        /// <param name="resDetailID"></param>
        /// <param name="finalPrice"></param>
        /// <returns></returns>
        public int UpdateReqDetail(string requestDetailID, string resDetailID, string finla_price, string finla_price_cn)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(@"update T_RequestDetail set ResDetailID='{0}',
						                                   finla_price='{1}',
						                                   finla_price_Cn='{2}'
					                                   where ReqDetailID='{3}'", resDetailID, finla_price, finla_price_cn, requestDetailID);
            return da.ExcuteNoQuery(sql.ToString());
        }
        /// <summary>
        /// 报价详情
        /// </summary>
        /// <param name="RequestID"></param>
        /// <returns></returns>
        public DataTable RequestDetailQuery(string RequestID)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(@"select RD.args03 EC,
	                               RD.args08 ZD,
	                               case when RD.args08='铸件' then m1.Material_code_z
			                            when RD.args08='锻件' then m1.Material_code end Body,
	                               case when RD.args08='铸件' then m2.Material_code_z
		                                when RD.args08='锻件' then m2.Material_code end Inside,
	                               case when RD.args08='铸件' then m3.Material_code_z
		                                when RD.args08='锻件' then m3.Material_code end Stick,
	                               case when RD.args08='铸件' then m4.Material_code_z
		                                when RD.args08='锻件' then m4.Material_code end Base,
	                               case when RD.args03='公制' then Size.Size_Code_C
	                                    when RD.args03='英制' then Size.Size_Code_S end size,
	                               case when RD.args03='公制' then PL.Pressure_Code_C
			                            when RD.args03='英制' then PL.Pressure_Code_S end press,
		                            CM.[Desc] conn,
		                            case when RD.args03='公制' then rd.args01+'℃'
			                             when RD.args03='英制' then RD.args01+'℉' end temp,
		                            RD.args010,
		                            RD.Query_num,
		                            rd.Buy_num,
		                            rd.deadline,
		                            isnull(rd.resdetailid,'') flag,
		                            DL.[Desc] design,
		                            FL.[desc] fran,
		                            SL.[Desc] struct,
		                            SE.Level ,
		                            SE.LevelType,
		                            case when RD.args08='铸件' then m5.Material_code_z
		                                when RD.args08='锻件' then m5.Material_code end fill,
		                            RD.rowstatus,RD.create_time
	                                from T_RequestDetail RD
                            left join  T_Request R on R.RequestID=RD.RequestID
                            left join T_Production_MultiLan PM on PM.ProductionID=RD.ProductionID and PM.LanId='zh'
                            LEFT join C_Material m1 on RD.MID_B=m1.MID
                            LEFT join C_Material m2 on RD.MID_I =m2.MID
                            LEFT join C_Material m3 on RD.MID_S=m3.MID
                            left join C_Material m4 on RD.args02=m4.MID
                            LEFT join C_Size Size on Size.SID=RD.SID
                            LEFT join C_PressureLevel PL on PL.PressureID=RD.PressureID
                            LEFT join C_Connection_MultiLan CM on CM.ConnID=RD.ConnID and CM.LanId='zh'
                            left join C_Material m5 on RD.args09=m5.MID
                            LEFT join C_DesignLevel DL on DL.DesignLevelID=RD.args04
                            LEFT join C_FranLevel FL on FL.FranLevelID=RD.args05
                            LEFT join C_StructLevel SL on SL.StructLevelID=RD.args06
                            LEFT join C_SealLevel SE on SE.SealLevelID=RD.args07

                            where RD.RequestID='{0}' order by RD.create_time desc", RequestID);
            return da.ExecuteDataTable(sql.ToString());
        }
        public DataTable getDataTable(string spName, Dictionary<string, object> param)
        {
            return da.GetDataTableBySPName(spName, param);
        }
        /// <summary>
        /// 获取对应的报价明细
        /// </summary>
        /// <param name="reqDetailID"></param>
        /// <returns></returns>
        public string getResDetail(string reqDetailID,out string status)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(@"select RD.ResDetailID,R.tauloginid from T_ResponseDetail RD
                                                left join T_Response R on RD.ResponseID=R.ResponseID
                                                 where ReqDetailID='{0}' and IS_Responsed='1'", reqDetailID);
            DataTable dt = da.ExecuteDataTable(sql.ToString());
            if (dt != null && dt.Rows.Count > 0)
            {
                if (dt.Rows.Count > 1)
                {
                    status = "1";//正常
                }
                else
                {
                    status = "0";//不正常
                }
                return dt.Rows[0]["ResDetailID"].ToString();
            }
            status = "0";//不正常
            return "";
        }
        public bool ExAl(ArrayList al)
        {
            return da.ExecuteArrayList(al);
        }
        #endregion
    }
}